package listbyorder.access001_100.test19;

import listbyorder.utils.ListNode;

/**
 * 删除链表的倒数第N个节点
 *
 * @author code_yc
 * @version 1.0
 * @date 2020/5/28 12:06
 */
public class Solution1 {

    // 方法一： 首先将链表进行反转
    // 然后删除第n个节点
    // 然后再将链表反转回来
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode resNode = reverse(head);
        // 删除第n个节点
        ListNode temp = resNode;
        ListNode res = null;
        if (n == 1) {
            res = temp.next;
        } else {
            while (n > 2) {
                temp = temp.next;
            }
            temp.next = temp.next.next;
            res = resNode;
        }
        return reverse(res);
    }

    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
